import jwt
from datetime import datetime, timedelta, timezone
from config import Config
from logger_config import get_logger

logger = get_logger(__name__)

def generate_token(user_data, config=None):
    """生成JWT令牌
    
    Args:
        user_data: 用户数据字典，必须包含'id'字段
        config: 配置对象，如果为None则使用默认Config
    
    Returns:
        JWT令牌字符串
    """
    if config is None:
        config = Config()
    
    payload = {
        'user_id': user_data['id'],
        'exp': datetime.now(timezone.utc) + timedelta(hours=config.JWT_EXPIRATION_HOURS),
        'iat': datetime.now(timezone.utc)
    }
    return jwt.encode(payload, config.JWT_SECRET_KEY, algorithm=config.JWT_ALGORITHM)

def verify_token(token, config=None):
    """验证JWT令牌
    
    Args:
        token: JWT令牌字符串
        config: 配置对象，如果为None则使用默认Config
    
    Returns:
        验证成功返回payload字典，失败返回None
    """
    if config is None:
        config = Config()
    
    try:
        logger.info(f"验证token: {token[:20]}...")
        logger.info(f"使用SECRET_KEY: {config.JWT_SECRET_KEY[:10]}...")
        payload = jwt.decode(token, config.JWT_SECRET_KEY, algorithms=[config.JWT_ALGORITHM])
        logger.info(f"Token验证成功，payload: {payload}")
        return payload
    except jwt.ExpiredSignatureError as e:
        logger.error(f"Token已过期: {e}")
        return None
    except jwt.InvalidTokenError as e:
        logger.error(f"Token无效: {e}")
        return None

def extract_token_from_header(auth_header):
    """从Authorization头中提取token
    
    Args:
        auth_header: Authorization头的值
    
    Returns:
        提取的token字符串，如果格式错误返回None
    """
    if not auth_header or not auth_header.startswith('Bearer '):
        return None
    
    try:
        return auth_header.split(' ')[1]
    except IndexError:
        return None

def estimate_token_count(text):
    """估算文本的token数量
    
    Args:
        text: 要估算的文本
    
    Returns:
        估算的token数量
    """
    if not text:
        return 0
    
    # 简单估算：英文约4个字符=1个token，中文约1.5个字符=1个token
    # 这是一个粗略估算，实际应该使用tiktoken等库
    chinese_chars = len([c for c in text if '\u4e00' <= c <= '\u9fff'])
    other_chars = len(text) - chinese_chars
    
    estimated_tokens = chinese_chars / 1.5 + other_chars / 4
    return int(estimated_tokens)